// let num_str = "9(10)"
/*
实现⼀个算法，⽀持任意2-16进制数之间转换，如：2进制转7进制，7进制转16进制，15进
制转8进制等。
 */

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    let mut iter = num_str.split("(");
    let num = iter.next().unwrap();
    // parse 10 from "10)"
    let base_from = iter
        .next()
        .unwrap()
        .trim_end_matches(")")
        .parse::<u32>()
        .unwrap();
    let mut converted_num = 0;
    let mut base = 1;
    for c in num.chars().rev() {
        let digit = match c {
            '0'..='9' => c as u32 - '0' as u32,
            'a'..='f' => c as u32 - 'a' as u32 + 10,
            _ => unreachable!(),
        };
        converted_num += digit * base;
        base *= base_from;
    }
    let mut result = String::new();
    while converted_num > 0 {
        let remainder = converted_num % to_base;
        let remainder_char = match remainder {
            0..=9 => (remainder as u8 + b'0') as char,
            10..=15 => (remainder as u8 - 10 + b'a') as char,
            _ => unreachable!(),
        };
        result.push(remainder_char);
        converted_num /= to_base;
    }
    result.chars().rev().collect()
}
